<template>
  <div id="app">
    <div id="loading" class="animated">
      <div class="loadbox">
        <div class="title">游戏加载中{{loadPerCent}}%</div>
        <div class="process"><div :style="{width:loadPerCent+'%'}"></div></div>
      </div>
    </div>
    <div id="game" ref="game">
      <!-- <div id="console"></div> -->
      <div id="loadingGif" v-if="loading"><div>loading</div></div>
      <div id="music"></div>
      <div id="menu" @click=" menuList = true"></div>
      <div id="menuList" :class="menuList ? 'active' : ''">
        <div class="close" @click=" menuList = false"></div>
        <div class="list_wrap">
        <a href="javascript:;" class="list0" @click="openRecord()"><i></i>记录</a>
        <a href="javascript:;" class="list1" @click="openCommission()"><i></i>积分</a>
        <a href="javascript:;" class="list2" @click="openRankingList()"><i></i>排行榜</a>
        <a href="javascript:;" class="list3" @click="openPayIn()"><i></i>充值</a>
        <a :href="item.href" v-for="(item,index) in menu.left_menu" :class="'list' + (index + 4) "><i></i>{{ item.title }}</a>
        </div>
      </div>
      <div id="help"  @click="helpOpen"></div>
      <a id="chongzhiBtn" href="/user.php?action=Withdrawals"></a>
      <div id="light"></div>
      <div id="score" class="number">
        <!--<span v-for="item in score.numberList" :class="'num num_' + item "></span>-->
      </div>
      <div id="total" class="number">
        <!--<span v-for="item in total.numberList" :class="'num num_' + item "></span>-->
      </div>
      <div id="run-item" ref="runItem">
        <div id="run-box" ref="runBox" class="animated infinite" :class="runBox.flash ? 'flashWin' : ''"></div>
        <div id="run-box" ref="runBoxLuck" class="animated infinite" :class="runBox.flash ? 'flashWin' : ''"></div>
        <div id="JPBtn" class="animated infinite " :class="JPBtnFlash"></div>
        <div id="centerScore" class="number">
          <div id="centerScoreNum" class="animated infinite " :class="centerScore.flash ? 'flashWin':''">
          </div>
        </div>
      </div>
      <div id="activeBtnGroup">
        <div class="addAll" 
          :class="btns.addAll.disabled ? 'disabled' : btns.addAll.keyDown ? 'active' : ''  "
          @mousedown="keyDown('addAll')" 
          @mouseup="keyUp('addAll')"
          @touchstart="keyDown('addAll')"  
          @touchend="keyUp('addAll')" 
          @click="clearAll">
        </div>
        <div class="leftBtn" :class="btns.leftBtn.disabled ? 'disabled' : btns.leftBtn.keyDown ? 'active' : ''  "
          @mousedown="keyDown('leftBtn')" 
          @mouseup="keyUp('leftBtn')"
          @touchstart="keyDown('leftBtn')"  
          @touchend="keyUp('leftBtn')" 
         @click="leftBtn"
         ></div>
        <div class="rightBtn" 
          :class="btns.rightBtn.disabled ? 'disabled' : btns.rightBtn.keyDown ? 'active' : ''  "
          @mousedown="keyDown('rightBtn')" 
          @mouseup="keyUp('rightBtn')"
          @touchstart="keyDown('rightBtn')"  
          @touchend="keyUp('rightBtn')" 
        @click="rightBtn"></div>
        <div class="range1" 
          :class="btns.range1.disabled ? 'disabled' : btns.range1.keyDown ? 'active' : ''  "
          @mousedown="keyDown('range1')" 
          @mouseup="keyUp('range1')"
          @touchstart="keyDown('range1')"  
          @touchend="keyUp('range1')" 
        @click="range1"></div>
        <div class="range2" 
        :class="btns.range2.disabled ? 'disabled' : btns.range2.keyDown ? 'active' : ''  "
          @mousedown="keyDown('range2')" 
          @mouseup="keyUp('range2')"
          @touchstart="keyDown('range2')"  
          @touchend="keyUp('range2')" 
        @click="range2"></div>
        <div class="start" 
        :class="btns.start.disabled ? 'disabled' : btns.start.keyDown ? 'active' : ''  "
          @mousedown="keyDown('start')" 
          @mouseup="keyUp('start')"
          @touchstart="keyDown('start')"  
          @touchend="keyUp('start')" 
        @click="goStart(this.event)"></div>
      </div>
      <div id="typeNumber">
        <div :class="typeNumber.box1.showAll ? 'box1 showAll' : 'box1'" >
          <div class="animated infinite " :class="typeNumber.box1.flash ? 'flashWin' : ''">
            <div :class="typeNumber.box1.value ? 'active_' + typeNumber.box1.value : ''">
              <span v-for="item in typeNumber.box1.numberList" :class="'num num_' + item"></span>
            </div>
          </div>
        </div>
        <div :class="typeNumber.box2.showAll ? 'box2 showAll' : 'box2'">
          <div class="animated infinite " :class="typeNumber.box2.flash ? 'flashWin' : ''">
            <div :class="typeNumber.box2.value? 'active_' + typeNumber.box2.value : ''">
              <span v-for="item in typeNumber.box2.numberList" :class="'num num_' + item"></span>
            </div>
          </div>
        </div>
      </div>
      <div id="optionNumber" class="number">
        <div id="btns_num_bar" class="list"></div>
        <div id="btns_num_seven" class="list"></div>
        <div id="btns_num_star" class="list"></div>
        <div id="btns_num_watermelons" class="list"></div>
        <div id="btns_num_alarm" class="list"></div>
        <div id="btns_num_coconut" class="list"></div>
        <div id="btns_num_orange" class="list"></div>
        <div id="btns_num_apple" class="list"></div>
        <!--<div class="list">
          <span v-for="item in btns.seven.numberList" :class="'num num_' + item "></span>
        </div>-->
      </div>

      <div id="optionBtnGroup">
        <div class="bar" 
          :class="btnsDisabled ? 'disabled' : btns.bar.keyDown ? 'active' : ''  "
          @mousedown="keyDown('bar')" 
          @mouseup="keyUp('bar')"
          @touchstart="keyDown('bar')"  
          @touchend="keyUp('bar')" 
          @click="optionBtn('bar')">
        </div>
        <div class="seven" :class="btnsDisabled ? 'disabled' : btns.seven.keyDown ? 'active' : ''  "
          @mousedown="keyDown('seven')" 
          @mouseup="keyUp('seven')"
          @touchstart="keyDown('seven')"  
          @touchend="keyUp('seven')" 
         @click="optionBtn('seven')"
         ></div>
        <div class="star" :class="btnsDisabled ? 'disabled' : btns.star.keyDown ? 'active' : ''  "
          @mousedown="keyDown('star')" 
          @mouseup="keyUp('star')"
          @touchstart="keyDown('star')"  
          @touchend="keyUp('star')" 
         @click="optionBtn('star')"
         ></div>
         <div class="watermelons" :class="btnsDisabled ? 'disabled' : btns.watermelons.keyDown ? 'active' : ''  "
          @mousedown="keyDown('watermelons')" 
          @mouseup="keyUp('watermelons')"
          @touchstart="keyDown('watermelons')"  
          @touchend="keyUp('watermelons')" 
         @click="optionBtn('watermelons')"
         ></div>
         <div class="alarm" :class="btnsDisabled ? 'disabled' : btns.alarm.keyDown ? 'active' : ''  "
          @mousedown="keyDown('alarm')" 
          @mouseup="keyUp('alarm')"
          @touchstart="keyDown('alarm')"  
          @touchend="keyUp('alarm')" 
         @click="optionBtn('alarm')"
         ></div>
         <div class="coconut" :class="btnsDisabled ? 'disabled' : btns.coconut.keyDown ? 'active' : ''  "
          @mousedown="keyDown('coconut')" 
          @mouseup="keyUp('coconut')"
          @touchstart="keyDown('coconut')"  
          @touchend="keyUp('coconut')" 
         @click="optionBtn('coconut')"
         ></div>
         <div class="orange" :class="btnsDisabled ? 'disabled' : btns.orange.keyDown ? 'active' : ''  "
          @mousedown="keyDown('orange')" 
          @mouseup="keyUp('orange')"
          @touchstart="keyDown('orange')"  
          @touchend="keyUp('orange')" 
         @click="optionBtn('orange')"
         ></div>
         <div class="apple" :class="btnsDisabled ? 'disabled' : btns.apple.keyDown ? 'active' : ''  "
          @mousedown="keyDown('apple')" 
          @mouseup="keyUp('apple')"
          @touchstart="keyDown('apple')"  
          @touchend="keyUp('apple')" 
         @click="optionBtn('apple')"
         ></div>
      </div>
    </div>
    <div id="dialog-opa" ref="dialogOpa" :class=" dialog.open ? 'animated fadeIn':' animated fadeOut'"></div>
      <div id="dialog" ref="dialog" :class=" dialog.open ? 'animated bounceIn':' animated bounceOut'">
        <div class="close" @click="dialogColse"></div>
        <div class="title">{{ dialog.title }}</div>
        <div class="body" ref="dialogContent"></div>
        <div class="footer" v-if="dialog.footer"></div>
    </div>
    <div class="dialog-menu" :class="Record.open ? 'active' : ''">
      <div class="dialog-opa"></div>
      <div class="dialog-menu-content">
        <!--<div ref="scrollLoadingWrapper" class="scroll-loading-wrapper" v-if="Record.loading"></div>-->
        <div class="title">记录</div>
        <div class="close" @click="Record.open = false"></div>
        <div class="body">
        <div class="clearfix" style="padding: 0 3px 5px;">
            <span class="pull-left name" >得分</span>
            <span class="pull-right" >时间</span>
        </div>
        <ul class="scrollBox" v-scroll="getRecord" :pause-scroll-trigger="Record.pauseScroll">
          <li v-for="item in Record.data ">
                <div class="clearfix">
                    <span class="pull-left name" >{{ item.score }}</span>
                    <span class="pull-right" >{{ item.time }}</span>
                </div>
            </li>
        </ul>
        </div>
      </div>
    </div>
    <div class="dialog-menu" :class="Commission.open ? 'active' : ''">
      <div class="dialog-opa"></div>
      <div class="dialog-menu-content">
        <div class="title">积分</div>
        <div class="close" @click="Commission.open = false"></div>
        <div class="body">
        <div class="totalMoney">总积分：<span>￥{{Commission.totalMoney}}</span></div>
        <div class="clearfix" style="padding: 0 3px;">
                <span class="pull-left name" >积分</span>
                <span class="pull-right" >时间</span>
            </div>
        <ul class="scrollBox" v-scroll="getCommission" :pause-scroll-trigger="Commission.pauseScroll">
          <li v-for="item in Commission.data ">
                <div class="clearfix">
                    <span class="pull-left name" >￥{{ item.money }}</span>
                    <span class="pull-right" >{{ item.time }}</span>
                </div>
            </li>
        </ul>
        </div>
      </div>
    </div>
    <div class="dialog-menu" :class="RankingList.open ? 'active' : ''">
      <div class="dialog-opa"></div>
      <div class="dialog-menu-content">
        <div class="title">排行榜</div>
        <div class="close" @click="RankingList.open = false"></div>
        <ul class="body scrollBox">
          <li v-for="item in RankingList.data " class="rankingList">
                <div class="clearfix">
                    <span class="pull-left name" >{{ item.order }} . {{ item.name }}</span>
                    <span class="pull-right" >￥{{ item.money }}</span>
                </div>
            </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import config from './config'
var dd= 0;
export default {
  name: 'app',
  components: {
  },
  computed:{
    runBoxWidth(){
      return (this.config.cardwidth/this.config.designWidth*10).toFixed(5)
    },
    runBoxHeight(){
      return (this.config.cardheight/this.config.designWidth*10).toFixed(5)
    },
    JPBtnFlash(){
      let className = ''
      if(this.isrun){
        className = 'light flash'
      }else if(this.JPBtn.flash){
        className = 'light flashWin'
      }else if(this.JPBtn.light){
        className = 'light'
      }
      return className
    },
  },
  data(){
    return {
      consoles:[],
      loading:true,
      audiosLoad:false,
      documentLoaded:false,
      loadPerCent:0,
      username:null,
      userid:null,
      menu:{
        left_menu:[],
        right_info:{
          title:'水果机玩法说明',
          content:''
        }
      },
      menuList:false,
      pay_list:{//充值列表
        title:'充值',
        content:''
      },
      config:{//以设计稿 宽度480px 为基准
        test:'http://wawa.s33a.cn/shuiguoji', 
        designWidth:480,//设计稿宽度
        runBgWidth:1024,//背景宽度
        cardwidth: 58,
        api:config.isDevelop ? '/api': '',
        cardheight: 57.5,
        betcardwidth: 87,
        betcardheight: 87,
        margin: 0,
        runboxlength: 4,//转圈个数
        runloop: 4,//转圈次数
        maxbet: 99,
        boxIndex:2,//40 30 20 ,20 15 10 对应的显示 0，1，2
        boxrate:{
          40:0,
          30:1,
          20:2,
          15:1,
          10:2,
        },
        boxrateArray:[40,30,20,15,10],
        maxOptionNumber:10,//底部按钮最大可输入分
        runNumberTime:1000,//数字滚动所需时间
      },
      betingResult:{//下注接口返回结果
        iswin:false,
        data:[]
      },
      multitype:{
          "b_bar": 100,
          "s_bar": 50,
          "b_seven": 40,
          "b_star": 30,
          "b_watermelons": 25,
          "b_alarm": 20,
          "b_coconut": 15,
          "b_orange": 10,
          "b_apple": 5,
          "small": 2,
          "cha": 0
      },
      piecelistPosition:{},
      piecelistmulti:{},
      piecelisttype:{},
      score:{
        divId:'score',
        value:0,//得分
        numberList:[0]
      },
      total:{
        divId:'total',
        value:0,//默认分
        numberList:[0]
      },
      betLastTime:{//上次下注的值
        total:0,
        flag:false,//是否可以操作
        data:[0,0,0,0,0,0,0,0],//分别对应下注按钮的上次下注值
      },
      thisBetValue:0,
      centerScore:{
        divId:'centerScoreNum',
        value:0,
        flash:false,
        numberList:[0]
      },
      JPBtn:{
        flash:false,//0 灰色，1闪烁，2 猜中闪烁
        light:false
      },
      runBox:{
        flash:false,
      },
      startbox:1,         //上次结果，此次的起点，初始化和currentshowlist的值对应 
      endbox:1,          //这是这次的结果
      jumpnum:1,        //这些需要算出来
      currentshowlist:[1],
      currentshowlistLuck:[],//中多个奖
      gametotal:0,//游戏所得分
      //状态值
      isgo:false,//点击go按钮，防止双击
      isResult:false,
      isrun:false,
      isRange:false,//点击go按钮，防止双击
      //定时器
      interval:null,
      mainDiv:null,
      selectRange:{
        disabled:false,
        value:0,// 0为默认 1 为 1-6 ；8 为 8-13 
      },
      btnsDisabled:false,//底部按钮禁止开关
      btns:{
        addAll:{keyDown:false,disabled:true},
        leftBtn:{keyDown:false,disabled:true,value:0},
        rightBtn:{keyDown:false,disabled:true,value:0},
        range1:{keyDown:false,disabled:true},
        range2:{keyDown:false,disabled:true},
        start:{keyDown:false,disabled:true},
        bar:{id:1,divId:'btns_num_bar',keyDown:false,disabled:true,isNum:true,value:0,numberList:[0],ogg:'Y208.mp3',typeOgg:'Y108.mp3'},
        seven:{id:2,divId:'btns_num_seven',keyDown:false,disabled:true,isNum:true,value:0,numberList:[0],ogg:'Y207.mp3',typeOgg:'Y107.mp3'},
        star:{id:3,divId:'btns_num_star',keyDown:false,disabled:true,isNum:true,value:0,numberList:[0],ogg:'Y206.mp3',typeOgg:'Y106.mp3'},
        watermelons:{id:4,divId:'btns_num_watermelons',keyDown:false,disabled:true,isNum:true,value:0,numberList:[0],ogg:'Y205.mp3',typeOgg:'Y105.mp3'},
        alarm:{id:5,divId:'btns_num_alarm',keyDown:false,disabled:true,isNum:true,value:0,numberList:[0],ogg:'Y204.mp3',typeOgg:'Y104.mp3'},
        coconut:{id:6,divId:'btns_num_coconut',keyDown:false,disabled:true,isNum:true,value:0,numberList:[0],ogg:'Y203.mp3',typeOgg:'Y103.mp3'},
        orange:{id:7,divId:'btns_num_orange',keyDown:false,disabled:true,isNum:true,value:0,numberList:[0],ogg:'Y202.mp3',typeOgg:'Y102.mp3'},
        apple:{id:8,divId:'btns_num_apple',keyDown:false,disabled:true,isNum:true,value:0,numberList:[0],ogg:'Y201.mp3',typeOgg:'Y101.mp3'},
      },
      typeNumber:{
        box1:{
          value:20,
          flash:false,
          showAll:false,
          numberList:[40,30,20]
        },
        box2:{
          value:10,
          flash:false,
          showAll:false,
          numberList:[20,15,10]
        }
      },
      items:{
        "0-0":{type: "orange",  list: 1,multi: "b_orange",bgX:-410,bgY:-822 },
        "0-1":{type: "alarm",  list: 2,multi: "b_alarm" ,bgX:-248,bgY:-100},
        "0-2":{type: "bar", list: 3,multi: "s_bar" ,bgX:-334,bgY:-15},
        "0-3":{type: "bar", list: 4,multi: "b_bar" ,bgX:-428,bgY:-941},
        "0-4":{type: "apple", list: 5,multi: "b_apple" ,bgX:-248,bgY:-272},
        "0-5":{type: "apple", list: 6,multi: "small" ,bgX:-248,bgY:-187},
        "0-6":{type: "coconut",  list: 7,multi: "b_coconut" ,bgX:-248,bgY:-445},
        "1-0":{type: "alarm",  list: 24,multi: "small" ,bgX:-248,bgY:-15},
        "2-0":{type: "apple", list: 23,multi: "b_apple" ,bgX:-248,bgY:-272},
        "3-0":{type: "cha", list: 22,multi: "cha" ,bgX:-322,bgY:-531},
        "4-0":{type: "star", list: 21,multi: "small" ,bgX:-342,bgY:-943},
        "5-0":{type: "star", list: 20,multi: "b_star" ,bgX:-236,bgY:-552},
        "6-0":{type: "coconut",  list: 19,multi: "b_coconut" ,bgX:-248,bgY:-445},
        "6-1":{type: "coconut",  list: 18,multi: "small" ,bgX:-248,bgY:-359},
        "6-2":{type: "apple", list: 17,multi: "b_apple" ,bgX:-248,bgY:-272},
        "6-3":{type: "seven",  list: 16,multi: "b_seven" ,bgX:-334,bgY:-187},
        "6-4":{type: "seven", list: 15,multi: "small" ,bgX:-334,bgY:-100},
        "6-5":{type: "alarm",  list: 14,multi: "b_alarm" ,bgX:-248,bgY:-100},
        "6-6":{type: "orange",  list: 13,multi: "b_orange" ,bgX:-410,bgY:-822},
        "5-6":{type: "orange", list: 12,multi: "small" ,bgX:-248,bgY:-187},
        "4-6":{type: "apple", list: 11,multi: "b_apple" ,bgX:-248,bgY:-272},
        "3-6":{type: "cha", list: 10,multi: "cha" ,bgX:-322,bgY:-617},
        "2-6":{type: "watermelons",  list: 9,multi: "small" ,bgX:-236,bgY:-638},
        "1-6":{type: "watermelons", list: 8,multi: "b_watermelons" ,bgX:-236,bgY:-724},
      },
      dialog:{//弹窗
        open:false,
        title:'消息',
        footer:false,
      },
      transformRequest:{
        headers: {
                  'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
        transformRequest: [function (data) {
            let ret = null
            for (let it in data) {
              if(ret){
                ret += '&' + encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) 
              }else{
                ret = encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
              }
            }
            return ret
        }]
      },
      Record:{//记录
        page:1,
        data:[],
        pauseScroll:false,
        open:false,
      },
      Commission:{//佣金
        page:1,
        data:[],
        totalMoney:0,
        pauseScroll:false,
        open:false,
      },
      RankingList:{//排行榜
        data:[],
        open:false,
      },
      music:{
        win:null,//中奖音乐
        type:'music_type_apply',//中奖类型音乐
      },
      audiosConfig:[{
          id:'music_win_fail',
          name:'fail.mp3'
        },{
          id:'music_win_luck_l',
          name:'Y110.mp3'
        },{
          id:'music_win_luck_r',
          name:'Y109.mp3'
        },{
          id:'music_btn_common',
          name:'Y210.mp3'
        },{
          id:'music_bigsamll_win',
          name:'Y112.mp3'
        },{
          id:'music_bigsamll_fail',
          name:'Y113.mp3'
        },{
          id:'music_bigsamll_run',
          name:'hit.mp3',
        },{
          id:'music_run_start',
          name:'Y021.mp3'
        },{
          id:'music_run_runing',
          name:'Y029.mp3',
          loop:true
        },{
          id:'music_run_end',
          name:'Y030.mp3'
        },{
          id:'music_run_end_one',
          name:'Y002.mp3'
        },{
          id:'music_win_more',
          name:'Y006.mp3',
        },{
          id:'music_win_more2',
          name:'Y004.mp3',
          loop:true
        },{
          id:'music_run_win_more',
          name:'Y009.mp3',
          loop:true
        },{
          id:'music_win_more_at',
          name:'Y001.mp3'
        },{
          id:'music_collect',
          name:'collect_coin_in.mp3'
        }],
      audiosConfigAfterLoad:[],
      audios:{},
      AudioContext:null,
    }
  },
  methods:{
    getData(){
      this.loading = true
      this.$http.get(this.config.api + '/user.php?action=initfruit').then((res) => {
          this.loading = false
          if (res.status == 200 && res.data.status == 1 ) {
              let data = res.data.data
              this.total.value = parseInt(data.money)
              
              this.username = data.name
              this.userid = data.uid
              this.config.maxOptionNumber = data.rate_limit
              this.menu.left_menu = data.left_menu
              let right_info_content = '';
              for (let i = 0; i < data.right_info.length; i++) {
                  right_info_content += `${ data.right_info[i] }<br>`
              }
              this.menu.right_info.content = right_info_content
              let payContent = `<div class="pay-list"><p>金额不够请充值！</p><ul class="list clearfix">`;
              for (let i = 0; i < data.pay_list.length; i++) {
                  payContent += `<li><a href="${ data.pay_list[i].url }">${ data.pay_list[i].name }</a></li>`
              }
              payContent += `</ul></div>`
              this.pay_list.content = payContent
              this.init()
              document.body.onbeforeunload = function(){
                return '您确定要退出游戏吗？'
              }
          } else {
                window.location.href = res.data.url
          }
      }, (err) => {
          this.loading = false
          this.dialogOpen('获取数据失败！')
      });
    },
    init() {
      let i, j, piecewidth, pieceheight, betwidth, betheight, tnhtml, piecehtml, bethtml, advwidth, advheight, advleft, advtop, bsheight;
      betheight = pieceheight;
      //初始化piece
      for (i = 0; i < 7; i++) {
                for (j = 0; j < 7; j++) {
                    if (i == 0 || j == 0 || i == 6 || j == 6) {
                        var tpinfo = this.items[i+'-'+j];
                        this.piecelistPosition[tpinfo.list] = { 
                          top:(i*this.runBoxHeight).toFixed(5),
                          left:(j*this.runBoxWidth).toFixed(5),
                          bgX:(tpinfo.bgX/this.config.designWidth*10).toFixed(5),
                          bgY:(tpinfo.bgY/this.config.designWidth*10).toFixed(5),
                          type:tpinfo.type,
                          multi:this.multitype[tpinfo.multi]
                        }
                        this.piecelistmulti[tpinfo.list] = this.multitype[tpinfo.multi];
                        this.piecelisttype[tpinfo.list] = tpinfo.type;
                    }
                }
            }
      this.showbox(this.startbox)
      //初始化默认得分和总分
      this.updateNumber(this.total)
      this.updateNumber(this.score)
      this.updateNumber(this.centerScore)
      this.btnsDisabled = false;
      this.disabledLRR1R2_btn(true)
      if(this.total.value == 0){
        this.btnsDisabled = true
        setTimeout(()=>{
          this.payIn()
        },1000)
      }
      //初始化下注分
      for (let key in this.btns) {
        if (this.btns[key].isNum) {
          this.updateNumber(this.btns[key])
        }
      }
      this.audiosSetting(this.audiosConfig)
    },
    openRecord(){
      //打开初始化窗口
      this.Record.open = true
      this.Record.page = 1
      this.Record.data = []
      this.Record.pauseScroll = false
      this.menuList = false
      this.getRecord()
    },
    getRecord(){
      if(this.Record.pauseScroll){
          return
      }
      this.loading = true
      this.$http.get(this.config.api + '/index.php?action=fruit&type=record&page=' + this.Record.page).then((res) => {
          this.loading = false
          if (res.status == 200 ) {
            if(res.data.length){
              this.Record.page++
              for (let i = 0; i < res.data.length; i++) {
                this.Record.data.push(res.data[i])
              }
            }else{
              this.Record.pauseScroll = true             
            }
          } else {
              this.dialogOpen('获取数据失败！')
          }
      }, (err) => {
          this.loading = false
          this.dialogOpen('获取数据失败！')
      });
    },
    openCommission(){
      this.Commission.open = true
      this.Commission.page = 1
      this.Commission.data = []
      this.Commission.pauseScroll = false
      this.menuList = false
      this.getCommission()
    },
    getCommission(){
      if(this.Commission.pauseScroll){
          return
      }
      this.loading = true
      this.$http.get(this.config.api + '/index.php?action=fruit&type=yongji&page=' + this.Commission.page).then((res) => {
          this.loading = false
          if (res.status == 200 ) {
            res.data.total && (this.Commission.totalMoney = res.data.total)
            if(res.data.data.length){
              this.Commission.page++
              for (let i = 0; i < res.data.data.length; i++) {
                this.Commission.data.push(res.data.data[i])
              }
            }else{
              this.Commission.pauseScroll = true             
            }
          } else {
              this.dialogOpen('获取数据失败！')
          }
      }, (err) => {
          this.loading = false
          this.dialogOpen('获取数据失败！')
      });
    },
    openRankingList(){
      this.RankingList.open = true
      this.RankingList.data = []
      this.menuList = false
      this.getRankingList()
    },
    getRankingList(){
      this.loading = true
      this.$http.get(this.config.api + '/index.php?action=fruit&type=paihangbang').then((res) => {
          this.loading = false
          if (res.status == 200 ) {
            if(res.data.length){
              this.RankingList.data = res.data
            }
          } else {
              this.dialogOpen('获取数据失败！')
          }
      }, (err) => {
          this.loading = false
          this.dialogOpen('获取数据失败！')
      });
    },
    openPayIn(){
      this.menuList = false
      this.payIn()
    },
    keyDown(btn){
      !this.btnsDisabled && (this.btns[btn].keyDown = true)
    },
    keyUp(btn){
        !this.btnsDisabled && (this.btns[btn].keyDown = false)
    },
    settingMusic(){
      for (let i = 1; i < 6; i++) {
        let winogg = 'C'+ (i < 10 ? '0'+ i : i);
        //if(i == 1){
          this.audiosConfig.push({
            id:`music_win_${i}`,
            name:`${winogg}.mp3`,
          });
        // }else{
        //   this.audiosConfigAfterLoad.push({
        //     id:`music_win_${i}`,
        //     name:`${winogg}.mp3`,
        //   });
        // }

      }
      //按钮点击声音,中奖类型声音
      for (var key in this.btns) {
        if (this.btns[key].isNum) {
          this.audiosConfig.push({
            id:`music_btn_${key}`,
            name:`${this.btns[key].ogg}`
          });
          this.audiosConfig.push({
            id:`music_type_${key}`,
            name:`${this.btns[key].typeOgg}`
          });
        }
      }
    },  
    audiosSetting(audioReSource){
      let _this = this;
      let audioIndex = 0;
      let context =  this.AudioContext;
      if(!context){
        try {
             context = new window.AudioContext();
             this.AudioContext = context;
          } catch (e) {
              console.log('!妳的浏览器不支持AudioContext:(');
              console.log(e);
          }
      }
      function initSound(obj,arrayBuffer) {
              context.decodeAudioData(arrayBuffer, function(buffer) { //解码成功时的回调函数
               _this.audios[obj.id] = {
                buffer : buffer,
                //context:context.createBufferSource(),
                source:null,
                loop:obj.loop
               }
              audioIndex++
              if( audioIndex < audioReSource.length){
                //!after && _this.loadPerCent++
                _this.loadPerCent++
                loadSoundFile(audioReSource[audioIndex]);
              }else if(audioIndex == audioReSource.length){
                //if(after){
                //   console.log('loading audios later ok ……')
                //}else{
                  _this.audiosLoad = true;
                  console.log('loading audios ok ……');
                  //_this.audiosSetting(_this.audiosConfigAfterLoad,'after')
                //}
              }
          }, function(e) { //解码出错时的回调函数
             _this.audiosLoad = true
             alert('您的浏览器不支持 webAudio 音频 ！')
              console.log('您的浏览器不支持 webAudio 音频 ！', e);
          });
          
      }
      function loadSoundFile(obj) {
        let url = './static/music/mp3/' + obj.name
          let xhr = new XMLHttpRequest(); //通过XHR下载音频文件
          xhr.open('GET', url, true);
          xhr.responseType = 'arraybuffer';
          xhr.onload = function(e) { //下载完成
              initSound(obj,xhr.response);
          };
          xhr.send();
      }
      context && loadSoundFile(audioReSource[0]);
    },
    closeLoading() {
      setTimeout(function(){
            document.getElementById('loading').className = 'animated fadeOutDown';
            setTimeout(function(){
              document.getElementById('loading').style.display = 'none';
            },800)
          },200)
    },
    musicPlay(id){
      try {
        let context = this.AudioContext//new window.AudioContext(); 
            this.audios[id].source = context.createBufferSource();
            this.audios[id].source.connect(context.destination);
            this.audios[id].source.buffer = this.audios[id].buffer;
            this.audios[id].loop && (this.audios[id].source.loop = true)
            this.audios[id].source.start(0)
      } catch (error) {
        this.console('playAudio','error')
        console.log(error)
      }
      
        //new this.audios[id]()
    },
    musicStop(id){
      try {
          if(this.audios[id].source){
            this.audios[id].source.stop(0)
            this.console('stopAudio','ok ...')
          }
      } catch (error) {
        console.log(error)
        this.console('stopAudio','error')
      }
    },
    isArray(obj) {
        return Object.prototype.toString.call(obj) === '[object Array]';
    },
    in_Array(arr, e) {
        for (let i = 0; i < arr.length; i++) {
            if (arr[i] == e)
                return true;
        }
        return false;
    },
    rand(min, max) {
        return parseInt(Math.random() * (max - min + 1) + min);
    },
    showbox(index,luck) {//显示单个或多个灯
        let i, len, tpleft = '', tptop = '', box = '',bgX = '',bgY = '';
        if (typeof (index) === 'number' && index > 0 && index < 25) {
            tpleft = this.piecelistPosition[index].left;
            tptop = this.piecelistPosition[index].top;
            bgX = this.piecelistPosition[index].bgX;
            bgY = this.piecelistPosition[index].bgY;
            box = "<div style='left:" + tpleft + "rem;top:" + tptop + "rem;background-position:" + bgX + "rem "+ bgY + "rem;' class='animated infinite '></div>";
        }
        else if (this.isArray(index) && index.length > 0) {
            len = index.length;
            for ( i = 0; i < len; i++) {
                tpleft = this.piecelistPosition[index[i]].left;
                tptop = this.piecelistPosition[index[i]].top;
                bgX = this.piecelistPosition[index[i]].bgX;
                bgY = this.piecelistPosition[index[i]].bgY;
                box += "<div style='left:" + tpleft + "rem;top:" + tptop + "rem;background-position:" + bgX + "rem "+ bgY + "rem;'></div>";
            }
            
        }
        if(luck){
          this.$refs.runBoxLuck.innerHTML = box;
        }else{
          this.$refs.runBox.innerHTML = box;
        }
        
    },
    changeshowlist(jumpindex) {//每次改变需要显示的box，返回速度
        var i,
            len = this.currentshowlist.length,
            jumpmax = this.jumpnum;
        switch (jumpindex) {
            case 0:
                var v = this.currentshowlist[0] + 1;
                this.currentshowlist.length = 0;
                v = v > 24 ? v - 24 : v;
                this.currentshowlist[0] = v;
                return 400;
            case 1:
                if (len == 1) {
                    var v = this.currentshowlist[0] + 1;
                    v = v > 24 ? v - 24 : v;
                    this.currentshowlist.push(v);
                }
                return 350;
            case 2:
                if (len == 2) {
                    var v = this.currentshowlist[1] + 1;
                    v = v > 24 ? v - 24 : v;
                    this.currentshowlist.push(v);
                }
                return 300;
            case 3:
                if (len == 3) {
                    var v = this.currentshowlist[2] + 1;
                    v = v > 24 ? v - 24 : v;
                    this.currentshowlist.push(v);
                }
                return 200;
            case jumpmax - 1:
                var v = this.currentshowlist[0] + 1;
                this.currentshowlist.length = 0;
                v = v > 24 ? v - 24 : v;
                this.currentshowlist[0] = v;
                return 800;
            case jumpmax - 2:
                var v = this.currentshowlist[0] + 1;
                this.currentshowlist.length = 0;
                v = v > 24 ? v - 24 : v;
                this.currentshowlist[0] = v;
                return 700;
            case jumpmax - 3:
                var v = this.currentshowlist[0] + 1;
                this.currentshowlist.length = 0;
                v = v > 24 ? v - 24 : v;
                this.currentshowlist[0] = v;
                return 600;
            case jumpmax - 4:
                var v = this.currentshowlist[0] + 1;
                this.currentshowlist.length = 0;
                v = v > 24 ? v - 24 : v;
                this.currentshowlist[0] = v;
                return 400;
            case jumpmax - 5:
                var v = this.currentshowlist[0] + 1;
                this.currentshowlist.length = 0;
                v = v > 24 ? v - 24 : v;
                this.currentshowlist[0] = v;
                return 300;
            case jumpmax - 6:
                var v = this.currentshowlist[1] + 1;
                this.currentshowlist.length = 0;
                v = v > 24 ? v - 24 : v;
                this.currentshowlist[0] = v;
                return 200;
            case jumpmax - 7:
                var v1 = this.currentshowlist[1] + 1;
                var v2 = this.currentshowlist[2] + 1;
                this.currentshowlist.length = 0;
                v1 = v1 > 24 ? v1 - 24 : v1;
                v2 = v2 > 24 ? v2 - 24 : v2;
                this.currentshowlist[0] = v1;
                this.currentshowlist[1] = v2;
                return 100;
            case jumpmax - 8:
                var v1 = this.currentshowlist[1] + 1;
                var v2 = this.currentshowlist[2] + 1;
                var v3 = this.currentshowlist[3] + 1;
                this.currentshowlist.length = 0;
                v1 = v1 > 24 ? v1 - 24 : v1;
                v2 = v2 > 24 ? v2 - 24 : v2;
                v3 = v3 > 24 ? v3 - 24 : v3;
                this.currentshowlist[0] = v1;
                this.currentshowlist[1] = v2;
                this.currentshowlist[2] = v3;
                return 50;
            default:
                for (i = 0; i < len; i++) {
                    this.currentshowlist[i]++;
                    if (this.currentshowlist[i] > 24) {
                        this.currentshowlist[i] -= 24;
                    }
                }
                return 20;
        }
    },
    changeshowlistLuck(jumpindex) {
        let v = this.currentshowlist[0] + 1
        v = v > 24 ? 1 : v
        this.currentshowlist.length = 0;
        this.currentshowlist[0] = v
        if(  jumpindex > this.jumpnum - 2){
          return 800
        }else if(jumpindex > this.jumpnum - 6){
          return 300
        }else{
          return 100
        }
    },
    run(endbox,luck,winIndex,setupLuck,rate) {
        let time = 100,
            v1 = null,
            v2 = null,
            loop = this.config.boxIndex > 0,
            boxIndex = this.config.boxIndex,
            shownum = 1,
            boxmax = this.config.runboxlength,
            runloopnum = 0,
            jumpmax = this.jumpnum,
            jumpindex = 0,
            timer = null;
            if(luck){
              var startbox = this.startbox
              this.currentshowlistLuck.push(this.startbox)
              this.showbox(this.currentshowlistLuck,luck);
              this.musicStop('music_win_more2')
              this.musicStop('music_run_win_more')
              this.musicPlay('music_run_win_more')
            }else{
              this.musicPlay('music_run_start')
            }
        let timerdo = (()=>{
            if(luck){
              time = this.changeshowlistLuck(jumpindex);
            }else{
              time = this.changeshowlist(jumpindex);
            }
            this.showbox(this.currentshowlist);
            if(winIndex === undefined){
              if( jumpindex == 5 ){
                this.musicPlay('music_run_runing')
              }
              if( jumpindex == jumpmax - 4 ){
                this.musicStop('music_run_runing')
                this.musicPlay('music_run_end')
              }
              if(jumpindex == jumpmax){
                this.musicPlay('music_run_end_one')
              }
            }
            jumpindex++;
            v1 = this.typeNumber.box1.numberList[boxIndex]
            v2 = this.typeNumber.box2.numberList[boxIndex]
            this.typeNumber.box1.value = v1
            this.typeNumber.box2.value = v2
            if(boxIndex == 2 || loop){
              boxIndex--
              if(boxIndex <= 0){
                loop = false
              }
            }else if(boxIndex == 0 || !loop){
              boxIndex++
              if(boxIndex == 2){
                loop = true
              }
            }else if(boxIndex < 0){
              boxIndex++
            }
            if (jumpindex >= jumpmax) {
                if(this.betingResult.iswin){
                  if(rate == 40 || rate == 30 || rate == 20 || rate == 15 || rate == 10){
                    boxIndex = this.config.boxrate[rate]
                    v1 = this.typeNumber.box1.numberList[boxIndex]
                    v2 = this.typeNumber.box2.numberList[boxIndex]
                    this.typeNumber.box1.value = v1
                    this.typeNumber.box2.value = v2
                  }
                }
                this.config.boxIndex = boxIndex;
                clearTimeout(timer);
                this.startbox = endbox
                setTimeout(()=>{ 
                  if(luck){
                        this.result(winIndex,setupLuck)
                    }else{
                      this.result();
                    }
                }, 200);
            }
            else {
                timer = setTimeout(timerdo, time);
            }
        })
        
        timerdo();
    },
    result(winIndex,setupLuck) {
        winIndex = winIndex || 0;
         let winbox,type;
        if(winIndex < this.betingResult.data.length){
           winbox = this.betingResult.data[winIndex].index + 1;
           type = this.piecelisttype[winbox];
        }
        let action = (()=>{
          winIndex++
          if(winIndex < this.betingResult.data.length){
            let endbox = this.betingResult.data[winIndex].index + 1
            let step = (endbox - this.startbox) > 0 ? endbox - this.startbox : 24 - this.startbox + endbox
            this.jumpnum = step //这些需要算出来
            let luck = true
            this.musicPlay('music_win_more_at')
            setTimeout(()=>{
                    this.music.type = 'music_type_' + type
                    this.musicPlay(this.music.type)
                  },500)
            setTimeout(()=>{
              this.run(endbox,luck,winIndex,undefined,this.betingResult.data[winIndex].is_rate)
            },1500)
          }
        })
        if (this.betingResult.iswin && winIndex < this.betingResult.data.length) {
            if(winIndex == 0){
              this.JPBtn.light = true //中JP灯亮
              this.flashing(true,'betWin')
              if(!setupLuck && (this.betingResult.data[winIndex].is_luck == 1 || 1 < this.betingResult.data.length)){
                this.musicPlay('music_win_more')
                setTimeout(()=>{
                  this.musicPlay('music_win_more2')
                }, 500);
              }
              this.btns.rightBtn.value = 0
                for (var key in this.btns) {//隐藏未命中的数值
                  if (this.btns[key].isNum && type !== key) {
                    this.clearNumber(this.btns[key])
                  }
                }
            }else{

            }
            if (this.betingResult.data[winIndex].is_luck == 1) {
              let luck_data = this.betingResult.data[winIndex].luck_data
              if(setupLuck){
                this.score.value = this.score.value + luck_data.score
                  this.updateNumber(this.score)
                  type = this.piecelisttype[luck_data.index + 1]
                  //this.btns[type].numberList = Array.from(this.btns[type].value.toString())
                  this.updateNumber(this.btns[type])
                  action()
              }else{
                this.musicPlay('music_win_more_at')
                if(type !== 'cha'){
                  setTimeout(()=>{
                    this.music.type = 'music_type_' + type
                    this.musicPlay(this.music.type)
                  },500)
                }
                setTimeout(()=>{
                  let endbox = luck_data.index + 1
                  let step = (endbox - this.startbox) > 0 ? endbox - this.startbox : 24 - this.startbox + endbox
                  this.jumpnum =  step //这些需要算出来
                  let luck = true,setupLuck = true;
                  let rate = this.betingResult.data[winIndex].luck_data.is_rate
                  this.run(endbox,luck,winIndex,setupLuck,rate)
                }, 1500);
              }
            }else{
              this.score.value = this.score.value + this.betingResult.data[winIndex].score;
              this.updateNumber(this.score)
              if(winIndex > 0){
                //this.btns[type].numberList = Array.from(this.btns[type].value.toString())
                this.updateNumber(this.btns[type])
              }
              action()
            }
        }else if(!this.betingResult.iswin){
            for (var key in this.btns) {//归零
            if (this.btns[key].isNum && this.btns[key].value > 0) {
              this.btns[key].value = 0
              this.updateNumber(this.btns[key])
            }
          }
        }
        if(winIndex >= this.betingResult.data.length || !this.betingResult.iswin){
            
            this.centerScore.value = 0
            this.updateNumber(this.centerScore)
            this.thisBetValue = 0
            //按钮启用
            this.btns.start.disabled = false
            this.isgo = false
            this.isrun = false;
            this.btns.leftBtn.value = this.score.value*2
            if(this.score.value == 0 && this.total.value == 0){
              this.btnsDisabled = true
            }else{
              this.btnsDisabled = false
            }
            if(this.betingResult.iswin){
              this.disabledLRR1R2_btn(false)//启用按钮
              this.musicStop('music_run_win_more')
              this.music.type = 'music_type_' + type
                this.musicPlay(this.music.type)
                setTimeout(()=>{
                  let rand = this.rand(1,5)
                  this.music.win = this.music.win && ('music_win_' + rand) || 'music_win_1';
                  this.musicPlay(this.music.win)
                },1000)
            }else{
              this.music.win = 'music_win_fail'
              this.musicPlay(this.music.win)
            }
        }
        this.isResult = true;
        
    },
    addAll(){
      //改功能已移除
      if(!this.btns.addAll.disabled && this.total.value >= 8 ){
        for (var key in this.btns) {
          if (this.btns[key].isNum && this.btns[key].value < this.config.maxOptionNumber) {
            this.updateNumber(this.total,-1)
            this.updateNumber(this.btns[key],1)
          }
        }
        this.musicPlay('music_btn_common')
      }
    },
    clearAll(){
      if(!this.btns.addAll.disabled){
        this.musicPlay('music_btn_common')
        if(this.betLastTime.total == 0){
          return
        }
        for (var key in this.btns) {
          if (this.btns[key].isNum ) {
              this.btns[key].value && (this.total.value += this.btns[key].value)
              this.btns[key].value = 0
              this.btns[key].numberList = [0]
              document.getElementById(this.btns[key].divId).innerHTML = `<span class="num num_0"></span>`
           }
        }
        this.updateNumber(this.total)
        this.betLastTime.flag = true
        this.thisBetValue = 0
        if(this.isResult && this.betingResult.iswin){
          this.musicStop(this.music.win)
          this.flashing(false)
        }
      }
    },
    leftBtn(){
      if(!this.btns.leftBtn.disabled && this.btns.leftBtn.value !== this.score.value ){
        this.total.value = this.total.value - this.btns.leftBtn.value + this.score.value
        this.score.value = this.btns.leftBtn.value
        this.updateNumber(this.score)
        this.updateNumber(this.total)
        this.musicPlay('music_btn_common')
        if(this.isResult && this.betingResult.iswin){
          this.musicStop(this.music.win)
          this.flashing(false)
        }
      }
    },
    rightBtn(){
      if(!this.btns.rightBtn.disabled ){
        if(this.score.value > 0){
          //this.btns.rightBtn.value++
          this.updateNumber(this.score,-1)
          this.updateNumber(this.total,1)
        }else{
          this.disabledLRR1R2_btn(true)
        }
        this.musicPlay('music_btn_common')
        if(this.isResult && this.betingResult.iswin){
          this.musicStop(this.music.win)
          this.flashing(false)
        }
      }
    },
    range1(){//1-6 点击
      if(this.btns.range1.disabled || this.isRange){
        return
      }
        if(!this.isRange){
          this.isRange = true
            this.selectRange.value = 1
            this.typeNumber.box1.showAll = true
            this.typeNumber.box2.showAll = false
            this.typeNumber.box2.value = null
            this.flashing(false)
            this.range(0)
        }
    },
    range2(){//8-13 点击
      if(this.btns.range2.disabled || this.isRange){return}
        if(!this.isRange){
          this.isRange = true
          this.selectRange.value = 2
          this.typeNumber.box2.showAll = true
          this.typeNumber.box1.showAll = false
          this.typeNumber.box1.value = null
          this.flashing(false)
          this.range(1)
        }
    },
    range(type){
      this.isrun = true
      let params = {
        is_big_small:type,
        score:this.score.value
      }
      let runing = ( data =>{
        let time = 100,
            v = 0,
            jumpindex = 0,
            jumpmax = 20,
            timer = null;
        this.musicStop(this.music.win)
        let timerdo = (()=>{
            v = this.rand(1, 13);
            jumpindex++;
            this.musicPlay('music_bigsamll_run')
            if (jumpindex >= jumpmax) {
                this.centerScore.value = data.num
                //this.centerScore.numberList = Array.from(data.num.toString())
                this.updateNumber(this.centerScore)
                clearTimeout(timer);
                setTimeout(()=>{
                  if(data.winning == 1){
                    setTimeout(()=>{
                      this.isRange  = false
                      this.score.value = data.score
                      this.leftBtn.value = data.score*2
                      this.updateNumber(this.score)
                      this.centerScore.value = 0
                      this.centerScore.numberList = [0]
                      document.getElementById(this.centerScore.divId).innerHTML = `<span class="num num_0"></span>`
                      let rand = this.rand(1,5)
                      this.music.win = 'music_win_' + rand
                      this.musicPlay(this.music.win)
                    },1500)
                    this.flashing(true,'guessSize')
                    this.musicPlay('music_bigsamll_win')
                  }else{
                    this.isRange  = false
                    this.musicPlay('music_bigsamll_fail')
                    this.score.value = 0
                    this.score.numberList = [0]
                    document.getElementById(this.score.divId).innerHTML = `<span class="num num_0"></span>`
                    this.restStart()
                  }
                  this.isrun = false;
                }, 200);
            }else {
              this.centerScore.value = v
              this.updateNumber(this.centerScore)
              //this.centerScore.numberList = Array.from(v.toString())
              if(jumpindex > jumpmax - 2){
                time = 500
              }
              timer = setTimeout(timerdo, time);
            }
        })
        timerdo();
      })
      this.console('range','压大小')
      this.$http.post(this.config.api + '/index.php?action=fruit&type=bigandsamll',params,this.transformRequest).then((res) => {
          this.loading = false
          
          if (res.status == 200) {
            this.console('range','压大小请求成功')
              runing(res.data)
          } else {
            this.console('range','压大小请求失败')
              this.isrun = false
              this.dialogOpen(res.data.tip)
              this.restStart()
          }
      }, (err) => {
        this.console('range','压大小请求报错')
          this.loading = false
          this.isrun = false
          this.dialogOpen(err.tip)
          this.restStart()
      });
      
    },
    disabledLRR1R2_btn(flag){//左右箭头按钮，1-6，1-6按钮 开关
      this.btns.leftBtn.disabled = flag
      this.btns.rightBtn.disabled = flag
      this.btns.range1.disabled = flag
      this.btns.range2.disabled = flag
    },
    goStart(e){
      if(!this.btns.start.disabled && !this.isgo && !this.isrun){
            //先将得分转过来
            this.isgo = true
            if( this.isResult && this.betingResult.iswin){//复位
              this.flashing(false)
              this.restStart()
            }else{
              this.start()
            }
      }
      this.console('isgo',this.isgo)
    },
    start(){
      this.console('start','开始……')
      if(this.music.win && !this.betingResult.iswin){
        this.musicStop(this.music.win)
      }
      this.console('start','停止音乐……')
      if(this.betLastTime.flag){
          if(this.betLastTime.total > this.total.value){
            //上次下注的分数 大于当前分数
            let clear = true
            this.isgo = false
            this.payIn(clear)
            return
          }
      }else{
        if(this.thisBetValue == 0 && this.betLastTime.total == 0){
            //this.dialogOpen('您的总分不够下注，请上分！')
            this.payIn()
            this.isgo = false
            return
          }else if(this.thisBetValue == 0){
              this.dialogOpen('请先下注！')
              this.isgo = false
              return
            }
      }
      let moneyIsOk = false,bet_id_array = [], bet_id_score_array = [];
      
      for (let key in this.btns) {
        if(this.btns[key].isNum ){
          let betLastTimeValue = this.betLastTime.data[this.btns[key].id - 1]
          if(this.betLastTime.flag && betLastTimeValue > 0){
              this.btns[key].value = betLastTimeValue
              this.updateNumber(this.btns[key])
            }
          if(this.btns[key].value > 0 ){
            //moneyIsOk = true
            bet_id_array.push(this.btns[key].id)
            bet_id_score_array.push(this.btns[key].value)
          }
        }
      }
      if(this.betLastTime.flag && this.betLastTime.total > 0){
          this.updateNumber(this.total,-this.betLastTime.total)
      }
      this.loading = true
      let params = {
        bet_id:bet_id_array,//isMore ? bet_id_array : bet_id,
        bet_id_score:bet_id_score_array//isMore ? bet_id_score_array : bet_id_score
      }
      let runing = (()=>{
        
        for (let key in this.btns) {
          if (!this.btns[key].isNum ) {//禁止非底部按钮点击状态
            this.btns[key].disabled = true
          }
        }
        this.btnsDisabled = true//禁止底部按钮点击状态
        //10,20,30,40 复位
        this.typeNumber.box1.showAll =false
        this.typeNumber.box2.showAll =false
        if(!this.typeNumber.box1.value){
          this.typeNumber.box1.value = this.typeNumber.box1.numberList[this.config.boxIndex]
        }
        if(!this.typeNumber.box2.value){
          this.typeNumber.box2.value = this.typeNumber.box1.numberList[this.config.boxIndex]
        }
        this.isrun = true
        this.betLastTime.flag = true
        let endbox = this.betingResult.data[0].index + 1
        //算出运行步数
        let step = (endbox - this.startbox) > 0 ? endbox - this.startbox : 24 - this.startbox + endbox
        this.jumpnum = 24 * this.config.runloop + step //这些需要算出来
        this.run(endbox,undefined,undefined,undefined,this.betingResult.data[0].is_rate)
      })
      let _data = {
        iswin:true,
        data:[{
          index:10,
          score:0,
          is_luck:1,
          is_rate:10,
          luck_data:{
            index:12,
            score:8,
            is_rate:40,
          }
        },{
          index:15,
          score:20,
          is_luck:0,
          is_rate:30,
          luck_data:null
        },{
          index:20,
          score:20,
          is_luck:0,
          is_rate:96,
          luck_data:null
        }]
      }
      this.console('start','开始请求……')
      this.$http.post(this.config.api + '/index.php?action=fruit&type=betting',params,this.transformRequest).then((res) => {
          this.loading = false
          if (res.status == 200 && res.data.data) {
            this.console('start','请求成功')
              this.betingResult.iswin = res.data.status == 1
              this.betingResult.data = res.data.data
              //this.betingResult = _data
              runing()
          } else {
            this.console('start','请求失败')
              this.dialogOpen('下注失败，请检查网络或重新登录')
              this.restStart()
          }
      }, (err) => {
          this.loading = false
          this.console('start','请求失败')
          this.dialogOpen('下注失败，请检查网络或重新登录')
          console.log(err.tip)
          this.restStart()
      });
      
    },
    restStart(){//复位开始
      this.console('restStart','复位开始……')
      if(this.score.value > 0){
          this.music.win && this.musicStop(this.music.win)
          this.musicStop(this.music.type)
          let score = this.score.value;
          this.runNumber(this.score,-score,true);
          this.runNumber(this.total,score,false);
          //this.runNumberMusic()
        }else{
          this.isgo = false
        }
        this.currentshowlistLuck = [];
        this.$refs.runBoxLuck.innerHTML = '';
        this.JPBtn.light = false; //中JP灯开关
        this.btnsDisabled = false;//启用底部加分按钮
        //禁用左右，选分范围按钮
        this.disabledLRR1R2_btn(true)
        this.btns.leftBtn.value = 0
        this.typeNumber.box1.showAll = false
        this.typeNumber.box2.showAll = false
        if(!this.typeNumber.box1.value){
        this.typeNumber.box1.value = this.typeNumber.box1.numberList[this.config.boxIndex]
        }
        if(!this.typeNumber.box2.value){
          this.typeNumber.box2.value = this.typeNumber.box1.numberList[this.config.boxIndex]
        }
        this.isResult = false
        this.isrun = false
        for (let key in this.btns) {//复位值为 0
          if (this.btns[key].isNum) {
            this.btns[key].value = 0
            this.btns[key].numberList = [0]
            document.getElementById(this.btns[key].divId).innerHTML = `<span class="num num_0"></span>`
          }
        }
      this.console('restStart','复位结束……')
    },
    optionBtn(btn){
      if(!this.btnsDisabled && this.btns[btn].value < this.config.maxOptionNumber  ){
        
        if(this.isResult && this.betingResult.iswin){
          this.btnsDisabled = true
          return
        }
        if(this.total.value == 0){
          this.payIn()
          return
        }
        if(this.betLastTime.flag){
          this.betLastTime.flag = false
          this.betLastTime.total = 0
          this.betLastTime.data = [0,0,0,0,0,0,0,0]
        }
        this.betLastTime.total += 1
        this.thisBetValue++ 
        this.betLastTime.data[this.btns[btn].id -1] += 1
        this.btns.start.disabled = false
        this.btns.addAll.disabled = false
        let btnMusic = 'music_btn_' + btn
        this.musicPlay(btnMusic)
        this.updateNumber(this.btns[btn],1)
        this.updateNumber(this.total,-1)
      }
    },
    updateNumber(obj,val){//更新数值
        val && (obj.value += val)
        obj.numberList = Array.from(obj.value.toString())
        let html = '';
        for (var i = 0; i < obj.numberList.length; i++) {
          html += `<span class="num num_${obj.numberList[i]}"></span>`
        }
        document.getElementById(obj.divId).innerHTML = html
    },
    clearNumber(obj){
      //obj.numberList = [];
      document.getElementById(obj.divId).innerHTML = '';
    },
    runNumber(obj,value,playAudio){//数字滚动
        if(value == 0){
          return
        }
				//difference 要执行动画的次数
        let difference = Math.abs(value)
        let time = 1000;//总共花毫秒数
        let t = 50;//一次花毫秒数
        //let n = time/t;
        let time_v = Math.round(difference/(time/t));
        time_v = time_v == 0 ? 1 : time_v;
        let m = difference/time_v;
        let n = Number.isInteger(m) ? m : Math.round(m);
        if(m < n){
          n -= 1
        }
        let timer
	  		let increase = (()=>{
	  			//执行次数为0时,停止执行
	  			if ( n < 1 ) {
            this.isgo = false
            if(!Number.isInteger(m)){
              let lv = difference%time_v
              let v = value > 0 && lv || -lv
              this.updateNumber(obj,v)
            }
	        	clearInterval(timer);
	        	return ;
	     		}
	  			n--;
          let v = value > 0 && time_v || - time_v
	        this.updateNumber(obj,v)
          playAudio && this.musicPlay('music_collect')
	      })
        timer = setInterval(increase,t);
		},
    flashing(flag,Class){//闪烁开关
      switch (Class) {
        case 'guessSize':
          this.centerScore.flash = flag
          this.runBox.flash = flag
          this.typeNumber['box'+this.selectRange.value].flash = flag
          break;
        case 'betWin':
          this.JPBtn.flash = flag
          this.runBox.flash = flag
          this.typeNumber.box1.flash = flag
          this.typeNumber.box2.flash = flag
          break;  
        default:
          this.JPBtn.flash = flag
          this.centerScore.flash = flag
          this.runBox.flash = flag
          this.typeNumber.box1.flash = flag
          this.typeNumber.box2.flash = flag
      }
    },
    dialogOpen(content,show = true,isContent = false){
        this.dialog.open = show
        this.$refs.dialogContent.innerHTML = isContent ? content : ('<div class="tip">'+ content +'</div>');
        this.$refs.dialogOpa.style.display = 'block'
        this.$refs.dialog.style.display = 'block'
        this.$refs.dialog.style.opacity = 0
        setTimeout(()=>{
              this.$refs.dialog.style.opacity = ''
        }, 150);
    },
    dialogColse(){
      this.dialog.open = false
      setTimeout(()=>{
        this.$refs.dialogOpa.style.display = 'none'
        this.$refs.dialog.style.display = 'none'
        this.dialog.title = '消息'
      }, 750);
    },
    helpOpen(){
      this.dialog.title = this.menu.right_info.title
      this.dialogOpen(this.menu.right_info.content,true,true);
    },
    payIn(clear){
      if(clear){

      }
      this.dialog.title = this.pay_list.title
      this.dialogOpen(this.pay_list.content,true,true);
    },
    console(name,status){
      //let conso = document.getElementById('console');
      //let html = `<div >${name}-----${status}</div>`
      //conso.innerHTML = conso.innerHTML + html;
      //conso.scrollTop = conso.scrollHeight;
      let cons = `${name}-----${status}`;
      console.log(cons)
    }
  },
  mounted(){
      this.settingMusic()
      this.getData()
       let loading = (()=>{
        if(document.readyState == 'complete'){ //当页面加载状态 
          this.documentLoaded = true
          this.loadPerCent += 100 - this.audiosConfig.length 
          console.log('document readyState complete ……')
        }
      })
      document.onreadystatechange = loading;//当页面加载状态改变的时候执行这个方法. 
      
  },
  created(){

  },
  watch:{
    audiosLoad:function(newValue,old){
      if(newValue && this.documentLoaded){
        this.closeLoading()
      }
    },
    documentLoaded:function(newValue,old){
      if(newValue && this.audiosLoad){
        this.closeLoading()
      }
    },
    isgo:function(newValue){
      this.console('isgo',newValue)
    }
  }
}
</script>
